package cn.tpshion.vm.common.model;

import cn.tpshion.vm.common.constant.ErrorCode;
import cn.tpshion.vm.common.exception.BizException;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> {

    private String code;

    private String msg;

    private T data;

    private long total;

    public Result(String code, String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> build(ErrorCode errorCode, T data){
        return new Result(errorCode.getCode(), errorCode.getMsg(), data);
    }

    public static <T> Result<T> ok(T data){
        return build(ErrorCode.OK, data);
    }

    public static <T> Result<T> ok(){
        return build(ErrorCode.OK, null);
    }

    public static Result fail(ErrorCode errorCode){
        return new Result(errorCode.getCode(), errorCode.getMsg(), null);
    }

    public static Result fail(String msg){
        return new Result(ErrorCode.FAIL.getCode(), msg, null);
    }

    public static Result error(BizException exception){
        return new Result(exception.getCode(), exception.getMsg(), null);
    }
}
